package whf.file.service;

import java.util.List;

import whf.file.dao.FileDAO;
import whf.file.entity.File;
import whf.framework.config.ApplicationConfig;
import whf.framework.exception.FindException;
import whf.framework.exception.NotFoundException;
import whf.framework.exception.RemoveException;
import whf.framework.exception.ServiceNotFoundException;
import whf.framework.file.IFile;
import whf.framework.file.IFolder;
import whf.framework.log.Log;
import whf.framework.log.LogFactory;
import whf.framework.util.BeanFactory;

/**
 * 服务对象具体实现，委托相应的dao对象实现相关操作
 * 
 * @author wanghaifeng
 * @email king@126.com
 * @modify 2006-11-14
 */
public class FileServiceImp extends whf.framework.service.ServiceImp<File> implements FileService {
	private static Log log = LogFactory.getLog(FileServiceImp.class);
	
	private FileDAO fileDAO;

	public void setFileDAO(FileDAO fileDAO) {
		this.fileDAO = fileDAO;
	}

	public static FileService getFileService() throws ServiceNotFoundException {
		return (FileService) BeanFactory.getService(FileServiceImp.class);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see whf.framework.file.IFileService#loadByFolder(whf.framework.file.IFolder)
	 */
	public List<IFile> loadByFolder(IFolder folder) throws FindException {
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see whf.framework.file.IFileService#loadFile(long)
	 */
	public IFile loadFile(long fileId) throws NotFoundException {
		return this.findByPrimaryKey(fileId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see whf.framework.file.IFileService#findByFileName(java.lang.String)
	 */
	public IFile findByFileName(String filename) throws FindException {
		List<File> files = this.fileDAO.find("t.phycialPath=?", filename);
		if (files.size() > 0) {
			return (IFile) files.get(0);
		} else {
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see whf.framework.service.ServiceImp#remove(whf.framework.entity.Entity)
	 */
	@Override
	public void remove(File entity) throws RemoveException {
		String filePath = ApplicationConfig.getInstance().getUploadDirectory() + entity.getPhycialPath();
		java.io.File file = new java.io.File(filePath);
		if (file != null && file.exists() && !file.isDirectory()) {
			file.delete();
			log.debug(filePath +" deleted successfully!");
		}
		super.remove(entity);
	}

}